using LF.Application.Services.interfaces;
using LF.Domain.Entities;
using LF.Domain.Services;
using LF.Application.Services.Iml;
using LF.Shared.Dtos.Out;
using LF.Shared.Dtos.Input;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;
using LF.Application.Extend;

namespace LF.Application.Services
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Sys)]
    public class RoleService: BaseService, IRoleService
    {
        IRoleManagerService _manager;
        public RoleService(IRoleManagerService manager, IObjectMapper<LFModule> mapper, IGlobalManagerService globalManager, ILogger<RoleService> logger):base(mapper,globalManager)
        {
            _manager = manager;
        }
        [LFAuthorize("角色列表", "system:role:list")]
        public Result<RoleSearchOut> List(RoleSearch search)
        {
            var result = _manager.All(search.Index, search.PageSize, search);
            var list = _mapper.Map<List<Role>, List<RoleOut>>(result);
            var count = _manager.Count(search);
            return Ok(new RoleSearchOut { Items = list, TotalCount = count });
        }
        [LFAuthorize("角色删除", "system:role:delete")]
        public Result RealDelete(Guid id)
        {
            if (_manager.RealDelete(id))
                return Ok();
            else
                return Error("删除失败!");
        }
        [LFAuthorize("角色详情", "system:role:read")]
        public Result<RoleOut> Get(Guid id)
        {
            var item = _manager.Get(id);
            var result = _mapper.Map<Role, RoleOut>(item);
            var menus=_globalManager.ToList<RoleMenu>(p=>p.RoleId==id);
            result.MenuIds=menus?.Select(p=>p.MenuId).ToList();
            return Ok(result);
        }
        [UnitOfWork]
        [HttpPost]
        [LFAuthorize("角色编辑", "system:role:create")]
        public Result Edit(RoleOut role)
        {
            bool result;
            var model = _mapper.Map<RoleOut, Role>(role);
            if (role.Id == null)
            {
                var old = _globalManager.Get<Role>(p => p.Name == role.Name);
                if (old != null)
                {
                    return Error("角色已存在!");
                }
                model.Id = Guid.NewGuid();
                result = _manager.Insert(model);
                if (role.MenuIds != null)
                {
                    var menus = new List<RoleMenu>(); 
                    foreach (var item in role.MenuIds)
                    {
                        menus.Add(new RoleMenu { MenuId=item,RoleId= model.Id });
                    }
                    _globalManager.Insert(menus);
                }
                

            }
            else
            {
                result = _manager.Update(model);
                _globalManager.RealDeleteByWhere<RoleMenu>(p=>p.RoleId==model.Id);
                if (role.MenuIds != null)
                {
                    var menus = new List<RoleMenu>();
                    foreach (var item in role.MenuIds)
                    {
                        menus.Add(new RoleMenu { MenuId = item, RoleId = model.Id });
                    }
                    _globalManager.Insert(menus);
                }
            }
            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        [UnitOfWork]
        public virtual Result Menus(List<RoleMenuOut> roles)
        {
            
            if (roles.IsNullOrEmpty())
            {
                return Error("权限为空");
            }
            var id = roles.First()!.RoleId;
            var role = _manager.Get(id);
            role.Menu = roles.Count;
            _manager.Update(role);
            _manager.ClearMenus(id);

            var menus = _mapper.Map<List<RoleMenuOut>, List<RoleMenu>>(roles);
            _manager.Inserts(menus);
            return Ok();
        }

        public Result<List<RoleMenuOut>> GetMenus(Guid id)
        {
            var list = _manager.Meuns(id);
            var result = _mapper.Map<List<RoleMenu>, List<RoleMenuOut>>(list);
            return Ok(result);
        }

        public Result<List<RoleOut>> GetRoles()
        {
            var list = _manager.All();
            var result = _mapper.Map<List<Role>, List<RoleOut>>(list);
            return Ok(result);
        }

        public Result UpdateRole(Guid id, RoleOut role)
        {
            if (id != role.Id)
            {
                return Error("ID不匹配!");
            }
            
            var model = _mapper.Map<RoleOut, Role>(role);
            bool result = _manager.Update(model);
            
            if (result)
                return Ok();
            else
                return Error("更新失败!");
        }
    }
}
